package org.ziegler.javabase.thread.scheduled;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.builder.ToStringBuilder;

public class Message implements Delayed {

    private final int id;
    private final long expire;

    public Message(int id, long delayMillis) {
        this.id = id;
        this.expire = System.currentTimeMillis() + TimeUnit.MILLISECONDS.toMillis(delayMillis);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("id", id)
                .append("expire", expire)
                .toString();
    }
}
